import { defineStore } from "pinia";
import { useEditorStore } from "./editor";
import {
  getAllArticles,
  addArticle,
  updateArticle,
  getArticleById,
  softDeleteArticle,
  getDeletedArticles,
  emptyRecycleBin,
  deleteArticle,
} from "@/services/articleService";
import { ElMessage, ElMessageBox } from "element-plus";

export const useArticleStore = defineStore("article", () => {
  const articles = ref<ArticleWithId[]>([]);
  const activeArticle = ref("");
  const lastUpdateTime = ref(0);
  const editorStore = useEditorStore();
  const recycleBinArticles = ref<ArticleWithId[]>([]);

  // 从 indexedDB 加载文章列表
  const loadArticles = async () => {
    articles.value = await getAllArticles();
    // 如果有打开的文章，设置为激活状态
    const openArticle = activeArticle.value
      ? { id: activeArticle.value }
      : articles.value.find((a) => a.isOpen);
    if (openArticle) {
      setActiveArticle(openArticle.id);
    }
  };

  // 创建新文章
  const createArticle = async (title: string) => {
    const now = Date.now();
    const article: ArticleWithId = {
      id: now.toString(),
      title: title || "未命名文章",
      content: "",
      createTime: now,
      updateTime: now,
      isOpen: true,
    };

    await addArticle(article);
    await loadArticles();
    setActiveArticle(article.id);
  };

  // 设置当前活动文章
  const setActiveArticle = async (id: string) => {
    const article = await getArticleById(id);
    if (article) {
      activeArticle.value = id;
      lastUpdateTime.value = article.updateTime;
      editorStore.content = article.content;
    }
  };

  // 更新文章内容
  const updateArticleContent = async (content: string) => {
    const article = await getArticleById(activeArticle.value);
    if (article) {
      // 只更新文章内容
      article.content = content;
      article.updateTime = Date.now();
      await updateArticle(article);
      await loadArticles();
    }
  };

  // 更新文章标题
  const updateArticleTitle = async (id: string, title: string) => {
    const article = await getArticleById(id);
    if (article) {
      article.title = title;
      article.updateTime = Date.now();
      lastUpdateTime.value = article.updateTime;
      await updateArticle(article);
    }
  };

  // 打开文章标签
  const openArticle = async (id: string) => {
    const article = await getArticleById(id);
    if (article) {
      if (!article.isOpen) {
        article.isOpen = true;
        await updateArticle(article);
        articles.value = await getAllArticles();
      }
      activeArticle.value = id;
    }
  };

  // 关闭文章标签
  const closeArticle = async (id: string) => {
    const article = await getArticleById(id);
    if (!article) return;

    // 软删除
    await softDeleteArticle(id);

    // 更新列表
    await loadArticles();

    // 切换活动文章
    if (id === activeArticle.value) {
      const openArticles = articles.value.filter((a) => a.isOpen);
      if (openArticles.length > 0) {
        await setActiveArticle(openArticles[0].id);
      } else {
        activeArticle.value = "";
        editorStore.setContent("");
      }
    }
  };

  // 获取打开的文章列表
  const openArticles = computed(() => {
    return articles.value.filter((article) => article.isOpen);
  });

  // 删除文章
  const deleteArticleById = async (id: string) => {
    const article = await getArticleById(id);
    if (article) {
      article.is_deleted = 1;
      article.delete_time = Date.now();
      await updateArticle(article);
      await loadArticles();
      await loadDeletedArticles();
    }
    loadArticles();
  };

  const activeArticleContent = computed(() => {
    const article = articles.value.find((a) => a.id === activeArticle.value);
    return article?.content || "";
  });

  const getActiveArticle = () => {
    return articles.value.find((a) => a.id === activeArticle.value);
  };

  // 加载回收站文章
  const loadDeletedArticles = async () => {
    recycleBinArticles.value = await getDeletedArticles();
    console.log(recycleBinArticles.value, "recycleBinArticles");
  };

  const restoreFromRecycle = async (id: string) => {
    const article = await getArticleById(id);
    if (article) {
      article.is_deleted = 0;
      delete article.delete_time;
      await updateArticle(article);
      await loadArticles();
      await loadDeletedArticles();
      ElMessage.success(`已恢复文章：${article.title}`);
    }
  };

  const deleteArticlePermanently = async (id: string) => {
    await ElMessageBox.confirm("确定要永久删除该文章吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await deleteArticle(id);
    await loadDeletedArticles();
    ElMessage.success("已永久删除文章");
  };

  const emptyRecycleBin = async () => {
    const deleted = await getDeletedArticles();
    await Promise.all(deleted.map((a) => deleteArticlePermanently(a.id)));
  };

  return {
    articles,
    activeArticle,
    lastUpdateTime,
    openArticles,
    createArticle,
    setActiveArticle,
    updateArticleContent,
    updateArticleTitle,
    closeArticle,
    openArticle,
    deleteArticleById,
    loadArticles,
    activeArticleContent,
    getActiveArticle,
    recycleBinArticles,
    loadDeletedArticles,
    emptyRecycleBin,
    restoreFromRecycle,
    deleteArticlePermanently,
  };
});
